package cn.modfun.web.core.utils;


import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;

import org.reflections.Reflections;
import org.reflections.scanners.ResourcesScanner;
import org.reflections.util.ClasspathHelper;
import org.reflections.util.ConfigurationBuilder;
import org.reflections.util.FilterBuilder;

import com.jfinal.kit.PathKit;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.druid.DruidPlugin;

import cn.hutool.core.util.StrUtil;
import cn.hutool.setting.Setting;
import cn.modfun.web.core.annotation.Model;

public class JFinalUtils {

	public static Setting config = new Setting("config/jfinal.txt");
	
	/**
	 * main方法启动jfinal
	 */
	public static void startPlugin() {
		/**
		 * 数据库插件
		 */
		Reflections reflections = new Reflections(new ConfigurationBuilder().setUrls(ClasspathHelper.forPackage("/")).setScanners(new ResourcesScanner()));
		Set<String> _sql = reflections.getResources(Pattern.compile(".*\\.stl"));
		Setting setting = new Setting("config/jdbc.txt");
		
		boolean isFirst = true;
		
		/* 多数据源的支持，根据jdbc.txt配置文件中的setting设置方式 */
		Map<String,DruidPlugin> dps = new HashMap<String,DruidPlugin>();
		for(String g : setting.getGroups()){
			if(dps.get(g)==null){
				dps.put(g, new DruidPlugin(setting.getByGroup("jdbcUrl", g), setting.getByGroup("user", g), setting.getByGroup("password", g)));
			}
			dps.get(g).start();
//			me.add(dps.get(g));
			ActiveRecordPlugin arp = new ActiveRecordPlugin(g,dps.get(g));
			arp.setBaseSqlTemplatePath(PathKit.getRootClassPath());
			arp.setDevMode(config.getBool("dev_mode", "common", false));
			arp.setShowSql(config.getBool("dev_mode", "common", false));
			arp.getEngine().addSharedMethod(new com.jfinal.kit.StrKit());
			
			
			/* 获得sqltemplate文件 */
			if(_sql!=null){
				for(String sql : _sql){
					arp.addSqlTemplate(sql);
				}
			}
			/* 添加模型 */
			Reflections _reflections = new Reflections(new ConfigurationBuilder().setUrls(ClasspathHelper.forPackage("")).filterInputsBy(new FilterBuilder().include(".+\\.model\\.[^\\.]+\\.class")));
			//Reflections _reflections = new Reflections(new ConfigurationBuilder().setUrls(ClasspathHelper.forPackage("/")).filterInputsBy(new FilterBuilder().include(".*\\.model\\.class")));
			Set<Class<?>> models = _reflections.getTypesAnnotatedWith(Model.class);
			if(models!=null){
				for(Class _m : models){
					Model m = (Model) _m.getAnnotation(Model.class);
					if((g.equals(m.ds())||(StrUtil.isBlank(m.ds()) && isFirst))){
						if(StrUtil.isBlank(m.key())){
							arp.addMapping(m.table(), _m);
						}else{
							arp.addMapping(m.table(),m.key(),_m);
						}
					}
				}
			}
//			me.add(arp);
			arp.start();
			isFirst = false;
		}
		
		
	}
}
